package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.OrderTo;
import com.atguigu.common.to.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.FareVo;
import com.atguigu.common.vo.MemberReceiveAddressVo;
import com.atguigu.common.vo.MemberRegisterVo;
import com.atguigu.common.vo.SkuHasStockVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WareFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import java.util.concurrent.ThreadPoolExecutor;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private MemberRegisterVo loginUser = LoginUserInterceptor.loginUser.get();

    private ThreadLocal<SubmitOrderVo> submitOrderVoThreadLocal = new ThreadLocal<>();


    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {

        OrderConfirmVo confirmVo = new OrderConfirmVo();
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {
            //1: 远程查询用户收货地址
            //设置老线程的数据同步
            RequestContextHolder.setRequestAttributes(attributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(loginUser.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> getCart = CompletableFuture.runAsync(() -> {
            //2: 远程查询购物车所有的购物项
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(cartItems);
        }, executor).thenRunAsync(() -> {
            //异步查询对应的sku的库存信息
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            //远程查询对应的sku的库存信息
            R r = wareFeignService.getSkuStock(collect);
            if (r.getCode() == 0) {
                List<SkuHasStockVo> stockVos = r.getDate("data", new TypeReference<List<SkuHasStockVo>>() {
                });
                if (!CollectionUtils.isEmpty(stockVos)) {
                    Map<Long, Boolean> map = stockVos.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                    confirmVo.setHasStock(map);
                }
            }
        }, executor);

        //3: 查询用户积分
        confirmVo.setIntergration(loginUser.getIntegration());

        //4:其他的价格,接受类里面已经自动计算
        //5: 防重令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId(), uuid, 30, TimeUnit.SECONDS);
        confirmVo.setOrderToken(uuid);

        try {
            CompletableFuture.allOf(getAddress, getCart).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return confirmVo;
    }

    @Override
    @Transactional
    public SubmitOrderResponseVo submitOrder(SubmitOrderVo vo) {
        submitOrderVoThreadLocal.set(vo);
        String userKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId();
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        responseVo.setCode(0);

        //1:验证令牌
        String scirpt = "if redis.call('get',(KEY[1])==ARGV[1] then return redis.call('del',KEYS[1] else return 0 end)";
        String token = vo.getOrderToken();
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(scirpt, Long.class), Arrays.asList(userKey), token);
        if (result == 0) {
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            //令牌验证成功,进行后续的下单操作
            //1:创建订单
            OrderCreateTo order = createOrder();
            //2:验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比,只要通过了,就继续做下面的事
                //3: 给数据库保存订单相关的数据
                saveOrder(order);
                //TODO 4: 锁定库存
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setTitle(item.getSkuName());
                    itemVo.setCount(item.getSkuQuantity());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(collect);

                //TODO 远程调用锁库存方法
                R r = wareFeignService.orderLock(lockVo);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    responseVo.setOrderEntity(order.getOrder());

                    //TODO 远程扣减积分
                    //订单创建成功,发送消息到rabbitmq
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return responseVo;
                } else {
                    //锁定失败
                    responseVo.setCode(2);
                    return responseVo;
                }

            } else {
                //没通过,就直接返回
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单
     **/
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())){
            //关单
            OrderEntity update = new OrderEntity();
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            update.setId(entity.getId());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);

            try {
                //保证消息百分百发送到MQ上,在数据库保存每一个消息的详细信息,包括消息的发送状态
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            } catch (AmqpException e) {
                //TODO 将没发送成功的消息进行重新发送,定期扫描数据库,将发送失败的消息再次发送给MQ
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = getOrderByOrderSn(orderSn);
        BigDecimal scale = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(scale.toString());

        //设置订单支付的备注说明,使用订单项中的信息来设置
        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = orderItemEntities.get(0);
        payVo.setOut_trade_no(orderSn);
        payVo.setBody(itemEntity.getSkuName());
        payVo.setSubject(itemEntity.getSpuBrand());

        return payVo;
    }

    @Override
    public PageUtils listWithItem(Map<String, Object> params) {

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",loginUser.getId()).orderByDesc("id")
        );

        List<OrderEntity> collect = page.getRecords().stream().map(item -> {

            List<OrderItemEntity> orderSn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("orderSn", item.getOrderSn()));
            item.setItemEntities(orderSn);
            return item;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝回调信息,修改订单状态
     **/
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);

        if ("TRADE_SUCCESS".equalsIgnoreCase(vo.getTrade_status()) || "TRADE_FINISHED".equalsIgnoreCase(vo.getTrade_status())){
            //支付成功,修改订单状态
            String tradeNo = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(tradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 创建秒杀订单
     **/
    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal totalAmount = orderTo.getSeckillPrice().multiply(new BigDecimal("" + orderTo.getNum()));
        orderEntity.setTotalAmount(totalAmount);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(orderTo.getOrderSn());
        itemEntity.setRealAmount(totalAmount);
        //TODO 根据SKUID远程查询sku相关信息进行设置
        itemEntity.setSkuQuantity(orderTo.getNum());
        orderItemService.save(itemEntity);

    }


    /**
     * 保存订单相关数据
     **/
    private void saveOrder(OrderCreateTo order) {
        baseMapper.insert(order.getOrder());
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        //1:生成订单号
        String orderSn = IdWorker.getTimeId();
        //2:创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //3:设置订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);

        //4: 验价
        computePrice(orderEntity, orderItems);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItems);

        return createTo;
    }

    /**
     * 计算价格
     **/
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        //订单的总额,叠加每一个订单项的总额信息
        for (OrderItemEntity entity : orderItems) {
            total = total.add(entity.getRealAmount());
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }

        //1:订单价格相关
        orderEntity.setTotalAmount(total);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //设置积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        //0代表未删除
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建所有订单项
     **/
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        if (!CollectionUtils.isEmpty(cartItems)) {
            List<OrderItemEntity> orderItem = cartItems.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return orderItem;
        }
        return null;
    }

    /**
     * 构建订单
     **/
    private OrderEntity buildOrder(String orderSn) {
        OrderEntity entity = new OrderEntity();
        MemberRegisterVo memberRegisterVo = LoginUserInterceptor.loginUser.get();
        entity.setMemberId(memberRegisterVo.getId());
        entity.setOrderSn(orderSn);
        //2:获取收货地址
        SubmitOrderVo submitOrderVo = submitOrderVoThreadLocal.get();
        R r = wareFeignService.getPrice(submitOrderVo.getAddrId());
        if (r.getCode() == 0) {
            //设置运费信息和收货人地址信息
            FareVo fareVo = r.getDate("data", new TypeReference<FareVo>() {
            });
            //运费
            entity.setFreightAmount(fareVo.getFare());

            MemberReceiveAddressVo addressVo = fareVo.getMemberReceiveAddressVo();
            entity.setReceiverCity(addressVo.getCity());
            entity.setReceiverDetailAddress(addressVo.getDetailAddress());
            entity.setReceiverName(addressVo.getName());
            entity.setReceiverPhone(addressVo.getPhone());
            entity.setReceiverPostCode(addressVo.getPostCode());
            entity.setReceiverProvince(addressVo.getProvince());
            entity.setReceiverRegion(addressVo.getRegion());

            //设置订单的相关默认信息,比如订单状态等等
            entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

            return entity;
        }
        return null;
    }

    /**
     * 创建每一个订单项信息
     **/
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1:商品的spu信息,远程查询spu相关信息
        R r = productFeignService.getInfoBySkuId(cartItem.getSkuId());
        if (r.getCode() == 0) {
            SpuInfoVo spuInfoVo = r.getDate("data", new TypeReference<SpuInfoVo>() {
            });
            itemEntity.setSpuId(spuInfoVo.getId());
            //TODO:要是想设置品牌名,就再次远程查询,这里暂时不做了
            itemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
            itemEntity.setSpuName(spuInfoVo.getSpuName());
            itemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }
        //2:商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = (String) StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //3:TODO 优惠信息(暂时不做)
        //4:积分信息 = 商品单机 * 商品个数
        Integer growCount = cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue();
        itemEntity.setGiftGrowth(growCount);
        itemEntity.setGiftGrowth(growCount);
        //5: 订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额 = 总价格减去各种优惠价格
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity()));
        BigDecimal realAmount = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(realAmount);

        return itemEntity;
    }
}